package service

import (
	"context"
	"fmt"
	"gitee.com/cristiane/micro-mall-search-cron/model/args"
	"gitee.com/cristiane/micro-mall-search-cron/model/elasticsearch"
	"gitee.com/cristiane/micro-mall-search-cron/pkg/code"
	"gitee.com/cristiane/micro-mall-search-cron/pkg/util"
	"gitee.com/cristiane/micro-mall-search-cron/proto/micro_mall_sku_proto/sku_business"
	"gitee.com/cristiane/micro-mall-search-cron/repository"
	"gitee.com/kelvins-io/common/errcode"
	"gitee.com/kelvins-io/common/json"
	"gitee.com/kelvins-io/kelvins"
	"time"
)

var (
	skuInventoryPageSize = 50
	skuInventoryPageNum  = 1
)

func SkuInventorySearchSyncTask() {
	ctx := context.Background()
	serverName := args.RpcServiceMicroMallSku
	conn, err := util.GetGrpcClient(ctx, serverName)
	if err != nil {
		kelvins.ErrLogger.Errorf(ctx, "GetGrpcClient %v,err: %v", serverName, err)
		return
	}
	//defer conn.Close()
	client := sku_business.NewSkuBusinessServiceClient(conn)
	count := 0
	for {
		if count > 5 {
			break
		}
		count++
		syncReq := &sku_business.SearchSyncSkuInventoryRequest{
			ShopId:   0,
			PageSize: int64(skuInventoryPageSize),
			PageNum:  int64(skuInventoryPageNum),
		}
		skuInventoryPageNum++
		syncRsp, rspErr := client.SearchSyncSkuInventory(ctx, syncReq)
		if rspErr != nil {
			kelvins.ErrLogger.Errorf(ctx, "SearchSyncSkuInventory %v,err: %v, req: %v", serverName, rspErr, json.MarshalToStringNoError(syncReq))
			return
		}
		if syncRsp.Common.Code != sku_business.RetCode_SUCCESS {
			kelvins.ErrLogger.Errorf(ctx, "SearchSyncSkuInventory req: %v, rsp: %v", json.MarshalToStringNoError(syncReq), json.MarshalToStringNoError(syncRsp))
			return
		}
		if syncRsp.Info == nil || len(syncRsp.Info) == 0 {
			break
		}
		storeSkuInventory(ctx, syncRsp.Info)
		time.Sleep(1 * time.Second)
	}
}

func storeSkuInventory(ctx context.Context, req []*sku_business.SkuInventoryInfo) {
	for i := 0; i < len(req); i++ {
		storeSkuInventoryOne(ctx, i, req[i])
	}
}

func storeSkuInventoryOne(ctx context.Context, workId int, req *sku_business.SkuInventoryInfo) {
	store := elasticsearch.SearchStoreSkuInventory{
		SkuCode:       req.SkuCode,
		Name:          req.Name,
		Title:         req.Title,
		SubTitle:      req.SubTitle,
		Desc:          req.Desc,
		Production:    req.Production,
		Color:         req.Color,
		Specification: req.Specification,
		ShopId:        req.ShopId,
	}
	body := json.MarshalToStringNoError(store)
	retCode := repository.SearchStore(ctx, elasticsearch.ESIndexSkuInventory, req.SkuCode, body)
	fmt.Printf("storeSkuInventoryOne workId: %d, req: %+v ,result: %v\n", workId, req.SkuCode, errcode.GetErrMsg(retCode))
	if retCode != code.Success {
		kelvins.ErrLogger.Errorf(ctx, "storeSkuInventoryOne req：%+v store retCode: %v", req, errcode.GetErrMsg(retCode))
	}
}
